<?php
require('header.php');
require('paginator.class.php');
requireAuth();

if(isset($_POST['csrf_token'])){
	if(isset($_POST['act'])){
		if($_POST['csrf_token'] == $_SESSION['cs_csrf_token']){
			deleteUser($userId);
			$facebook = new Facebook($fbconfig);
			session_destroy();
			$facebook->destroySession();

			makeRedirect(route('login'));
		}
	}
}
if(isset($_POST['tz'])){
	if(optTimeZone($_POST['tz'])){
		$tz = cleanValue($_POST['tz']);
		$strPwd = '';
		if(strlen($_POST['password']) > 5 && md5($_POST['password']) == md5($_POST['repassword'])){
			$pwd = generateSaltedPassword($_POST['password']);
			$strPwd = ", user_password='{$pwd}'";
		}
		// user settings
		// all input named begin with us_ will be encoded and save to user_setting_data field of users table
		$arrUserSetting = array();
		foreach($_POST as $pkey => $pval){
			if(strstr($pkey, 'us_')){
				$arrUserSetting[$pkey] = cleanValue($pval);
			}
		}
		$userSettings = json_encode($arrUserSetting);
		$_SESSION['cs_user_settings'] = $userSettings;
		if(mysql_query("UPDATE users SET `user_timezone`='" . $tz . "', `user_setting_data`='{$userSettings}' {$strPwd} WHERE user_id='" . $_SESSION['cs_user_id'] . "'")){
			// update postable pages
			mysql_query("UPDATE pages SET page_postable='NO' WHERE user_id=" . $userId);
			mysql_query("UPDATE groups SET group_postable='NO' WHERE user_id=" . $userId);
			if(!empty($_POST['pages'])){
				foreach($_POST['pages'] as $idx => $fbPageId){
					if(!empty($_SESSION['cs_user_pages']) && !array_key_exists($fbPageId, $_SESSION['cs_user_pages'])){
						unset($_POST['pages'][$idx]);
					}
					else{
						$_POST['pages'][$idx] = cleanValue($_POST['pages'][$idx]);
					}
				}
			}
			if(!empty($_POST['pages'])){
				mysql_query("UPDATE pages SET page_postable = 'YES' WHERE fb_page_id IN(" . implode(',', $_POST['pages']) . ") AND user_id=" . $userId);
			}
			// update groups
			if(!empty($_POST['groups'])){
				foreach($_POST['groups'] as $idx => $fbPageId){
					if(!empty($_SESSION['cs_user_groups']) && !array_key_exists($fbPageId, $_SESSION['cs_user_groups'])){
						unset($_POST['groups'][$idx]);
					}
					else{
						$_POST['groups'][$idx] = cleanValue($_POST['groups'][$idx]);
					}
				}
			}
			if(!empty($_POST['groups'])){
				mysql_query("UPDATE groups SET group_postable = 'YES' WHERE fb_group_id IN(" . implode(',', $_POST['groups']) . ") AND user_id=" . $userId);
			}
			echo '<div class="alert alert-success" style="text-align: center;">Settings saved.</div>';
			$_SESSION['cs_user_timezone'] = $tz;
		}
		else{
			echo '<div class="alert alert-error" style="text-align: center;">Error when saving settings.</div>';
		}
	}
}
?>
<div class="well">
	<div class="pull-right">
		<form id="frmDelete" action="" method="post"><button type="submit" id="btn-delete" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span> Delete my account</button>
			<input type="hidden" name="act" value="delete">
			<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['cs_csrf_token'] ?>">
		</form>
	</div>

	<form class="form-horizontal" role="form" method="post">
		<div class="form-group fg-username">
			<label class="col-sm-4 control-label">Facebook application setting</label>
			<div class="col-sm-4">
			    <label class="radio-inline">
			      <input type="radio" name="fb_app_setting" id="fb_app_setting_default" value="default" checked> Use default
			    </label>

			    <label class="radio-inline">
			      <input type="radio" name="fb_app_setting" id="fb_app_setting_own" value="own"> Use my own Facebook App
			    </label>
			</div>
		</div>
		<div id="app_setting" style="display:none;">
			<div class="form-group fg-username">
			    <label for="app_id" class="col-sm-4 control-label">Facebook App ID</label>
			    <div class="col-sm-4">
			       <input name="us_app_id" value="<?php echo getUserSettings('us_app_id') ?>" class="form-control" id="app_id" type="text" style="max-width: 400px;">
			    </div>
			</div>
			<div class="form-group fg-username">
			    <label for="app_secret" class="col-sm-4 control-label">Facebook App Secret</label>
			    <div class="col-sm-4">
			       <input name="us_app_secret" class="form-control" value="<?php echo getUserSettings('us_app_secret') ?>" id="app_secret" type="text" style="max-width: 400px;">
			    </div>
			</div>
			<hr />
		</div>
		<div class="form-group fg-username">
		    <label for="tz" class="col-sm-4 control-label">Time zone</label>
		    <div class="col-sm-4">
		      <select name="tz" class="form-control" id="tz" style="max-width: 400px;">
		      	<?php echo optTimeZone($_SESSION['cs_user_timezone']) ?>
		      </select>
		    </div>
		</div>
	  	<div class="form-group">
		    <label for="pages" class="col-sm-4 control-label">Postable fan pages</label>
		    <div class="col-sm-8">
		      <select name="pages[]" class="form-control" id="pages" multiple style="max-width: 400px;">
		      	<?php
		      	echo getOptPage(true, true);
		      	?>
		      </select>
		    </div>
		</div>
	  	<div class="form-group">
		    <label for="groups" class="col-sm-4 control-label">Postable groups</label>
		    <div class="col-sm-8">
		      <select name="groups[]" class="form-control" id="groups" multiple style="max-width: 400px;">
		      	<?php
		      	echo getOptGroup(true, true);
		      	?>
		      </select>
		    </div>
		</div>
		<hr />
		<div class="alert alert-info text-center">Leave blank if you dont want to change current password</div>
	  	<div class="form-group">
		    <label for="password" class="col-sm-4 control-label">New password</label>
		    <div class="col-sm-8">
		      <input name="password" class="form-control" id="password" type="password" style="max-width: 400px;">
		    </div>
		</div>
	  	<div class="form-group">
		    <label for="repassword" class="col-sm-4 control-label">Re-type new password</label>
		    <div class="col-sm-8">
		      <input name="repassword" class="form-control" id="repassword" type="password" style="max-width: 400px;">
		    </div>
		</div>
		<div class="form-group">
			<div class="col-sm-offset-4 col-sm-8">
			  <button type="submit" id="btn-save" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span> Save settings</button>
			</div>
		</div>
	</form>
</div>
<script type="text/javascript">
$(function(){
	$('#frmDelete').submit(function(){
		if(!confirm('Are you sure want to delete this account and all related infomations ?')) return false;
	});
	$('input[name="fb_app_setting"]').change(function(){
		if($(this).val() == 'own'){
			$('#app_setting').fadeIn().show();
		}
		else{
			$('#app_secret').val('');
			$('#app_id').val('');
			$('#app_setting').fadeOut().hide();
		}
	});
	if($('#app_secret').val() != '' && $('#app_id').val() != ''){
		$('#fb_app_setting_own').prop('checked', true);
		$('input[name="fb_app_setting"]').trigger('change');
	}
});
</script>
<?php require('footer.php') ?>